package org.gdstash.ui;

import com.jidesoft.utils.Lm;
import org.gdstash.db.*;
import org.gdstash.file.ARCList;
import org.gdstash.file.ARZDecompress;
import org.gdstash.file.IniConfig;
import org.gdstash.ui.character.GDCharEditPane;
import org.gdstash.ui.character.GDCharInventoryPane;
import org.gdstash.ui.character.GDCharMasteryImagePane;
import org.gdstash.ui.character.GDCharMasteryPane;
import org.gdstash.ui.util.GDCharInfoList;
import org.gdstash.ui.util.GDStashInfoList;
import org.gdstash.util.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

public class GDStashFrame extends JFrame {
    public static final boolean canSave = true;
    public static final boolean showRNGNumbers = false;
    public static final boolean showARZExport = false;
    public static final boolean compressedExport = true;
    public static final boolean importModItemsOnly = false;
    public static final boolean extraItemTypes = false;
    public static final boolean sqlDebug = false;
    public static final boolean suppressTagWarnings = true;
    public static final String PROGRAM_VERSION = "v1.8.0d";
    public static final boolean logDetail = false;
    public static final String GDDB_VERSION = "1.8.0";
    private static final boolean logInfo = false;
    public static final String CONFIG_VERSION = "1.0.8";
    public static boolean expansionFangsOfAsterkarn;
    public static DBConfig dbConfig;
    public static IniConfig iniConfig;
    public static DBEngineGame engineGame;
    public static DBEnginePlayer enginePlayer;
    public static DBEngineLevel engineLevel;
    public static ARZDecompress arz;
    public static ARCList arcList;
    public static boolean expansionAshesOfMalmouth;
    public static boolean expansionForgottenGods;
    public static GDSplashScreen splash;
    private static DefaultComboBoxModel<DBAffix> dmCompletion;
    private static DefaultComboBoxModel<DBAffix> dmModifier;
    private static DefaultComboBoxModel<DBAffix> dmModifierCelestial;
    private static List<String> logList;
    public GDTabbedPane pnlTabbed;
    public GDTransferPane pnlTransfer;
    public GDCharInventoryPane pnlCharInventory;
    public GDCraftPane pnlCraft;
    public GDCharEditPane pnlCharEdit;
    public GDMasteryInfoPane pnlMasteryInfo;
    public GDCollectionTabbedPane pnlCollection;
    public GDMassImportPane pnlMassImport;
    public GDConfigPane pnlConfig;
    public SystemTray tray;
    private PopupMenu trayMenu;

    static {
        GDStashFrame.dbConfig = null;
        GDStashFrame.iniConfig = null;
        GDStashFrame.engineGame = null;
        GDStashFrame.enginePlayer = null;
        GDStashFrame.engineLevel = null;
        GDStashFrame.expansionAshesOfMalmouth = false;
        GDStashFrame.expansionForgottenGods = false;
        GDStashFrame.expansionFangsOfAsterkarn = false;
        try {
            setGDLocale("English", null);
            GDMsgFormatter.readHTMLResourceBundle();
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
            GDMsgLogger.printStackTrace(ex);
            System.exit(1);
        }
        GDStashFrame.iniConfig = IniConfig.get();
        if (GDStashFrame.iniConfig.sectDir.gdPath != null && !GDStashFrame.iniConfig.sectDir.gdPath.isEmpty()) {
            String s = GDStashFrame.iniConfig.sectDir.gdPath + GDConstants.FILE_SEPARATOR + "gdx1" + GDConstants.FILE_SEPARATOR + "database" + GDConstants.FILE_SEPARATOR + "GDX1.arz";
            final File fGDX1 = new File(s);
            GDStashFrame.expansionAshesOfMalmouth = fGDX1.exists();
            s = GDStashFrame.iniConfig.sectDir.gdPath + GDConstants.FILE_SEPARATOR + "gdx2" + GDConstants.FILE_SEPARATOR + "database" + GDConstants.FILE_SEPARATOR + "GDX2.arz";
            final File fGDX2 = new File(s);
            GDStashFrame.expansionForgottenGods = fGDX2.exists();
            s = GDStashFrame.iniConfig.sectDir.gdPath + GDConstants.FILE_SEPARATOR + "gdx3" + GDConstants.FILE_SEPARATOR + "database" + GDConstants.FILE_SEPARATOR + "GDX3.arz";
            final File fGDX3 = new File(s);
            GDStashFrame.expansionFangsOfAsterkarn = fGDX3.exists();
        }
        GDImagePool.loadLogos();
        GDImagePool.loadImages();
        try {
            GDDBData.createConfigTables();
        } catch (SQLException ex2) {
            System.out.println(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "ERR_INIT_DB"));
            System.out.println(ex2.getMessage());
            while (ex2.getNextException() != null) {
                ex2 = ex2.getNextException();
                System.out.println(ex2.getMessage());
            }
            GDMsgLogger.printStackTrace(ex2);
            System.exit(1);
        }
        readDBConfig(null);
        try {
            setGDLocale(GDStashFrame.iniConfig.sectUI.language, null);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
            GDMsgLogger.printStackTrace(ex);
            System.exit(1);
        }
        final GDLog logStash = new GDLog();
        GDStashInfoList.findStashes(null, null, logStash);
        GDCharInfoList.findChars(null, null);
        if (GDStashFrame.dbConfig.configInit && GDStashFrame.dbConfig.gddbInit) {
            GDStashFrame.splash = new GDSplashScreen();
        } else {
            GDStashFrame.splash = null;
            logStash.clear();
        }
        GDImagePool.loadTiles();
        try {
            Class.forName("com.jtattoo.plaf.acryl.AcrylLookAndFeel", false, ClassLoader.getSystemClassLoader());
            UIManager.installLookAndFeel("JTattoo - Acryl", "com.jtattoo.plaf.acryl.AcrylLookAndFeel");
        } catch (ClassNotFoundException ex3) {
        }
        try {
            Class.forName("com.jtattoo.plaf.aero.AeroLookAndFeel", false, ClassLoader.getSystemClassLoader());
            UIManager.installLookAndFeel("JTattoo - Aero", "com.jtattoo.plaf.aero.AeroLookAndFeel");
        } catch (ClassNotFoundException ex4) {
        }
        try {
            Class.forName("com.jtattoo.plaf.aluminum.AluminumLookAndFeel", false, ClassLoader.getSystemClassLoader());
            UIManager.installLookAndFeel("JTattoo - Aluminum", "com.jtattoo.plaf.aluminum.AluminumLookAndFeel");
        } catch (ClassNotFoundException ex5) {
        }
        try {
            Class.forName("com.jtattoo.plaf.fast.FastLookAndFeel", false, ClassLoader.getSystemClassLoader());
            UIManager.installLookAndFeel("JTattoo - Fast", "com.jtattoo.plaf.fast.FastLookAndFeel");
        } catch (ClassNotFoundException ex6) {
        }
        try {
            Class.forName("com.jtattoo.plaf.graphite.GraphiteLookAndFeel", false, ClassLoader.getSystemClassLoader());
            UIManager.installLookAndFeel("JTattoo - Graphite", "com.jtattoo.plaf.graphite.GraphiteLookAndFeel");
        } catch (ClassNotFoundException ex7) {
        }
        try {
            Class.forName("com.jtattoo.plaf.luna.LunaLookAndFeel", false, ClassLoader.getSystemClassLoader());
            UIManager.installLookAndFeel("JTattoo - Luna", "com.jtattoo.plaf.luna.LunaLookAndFeel");
        } catch (ClassNotFoundException ex8) {
        }
        try {
            Class.forName("com.jtattoo.plaf.mcwin.McWinLookAndFeel", false, ClassLoader.getSystemClassLoader());
            UIManager.installLookAndFeel("JTattoo - McWin", "com.jtattoo.plaf.mcwin.McWinLookAndFeel");
        } catch (ClassNotFoundException ex9) {
        }
        try {
            Class.forName("com.jtattoo.plaf.mint.MintLookAndFeel", false, ClassLoader.getSystemClassLoader());
            UIManager.installLookAndFeel("JTattoo - Mint", "com.jtattoo.plaf.mint.MintLookAndFeel");
        } catch (ClassNotFoundException ex10) {
        }
        try {
            Class.forName("com.jtattoo.plaf.smart.SmartLookAndFeel", false, ClassLoader.getSystemClassLoader());
            UIManager.installLookAndFeel("JTattoo - Smart", "com.jtattoo.plaf.smart.SmartLookAndFeel");
        } catch (ClassNotFoundException ex11) {
        }
        try {
            Class.forName("com.jtattoo.plaf.hifi.HiFiLookAndFeel", false, ClassLoader.getSystemClassLoader());
            UIManager.installLookAndFeel("JTattoo - HiFi (dark)", "com.jtattoo.plaf.hifi.HiFiLookAndFeel");
        } catch (ClassNotFoundException ex12) {
        }
        try {
            Class.forName("com.jtattoo.plaf.noire.NoireLookAndFeel", false, ClassLoader.getSystemClassLoader());
            UIManager.installLookAndFeel("JTattoo - Noire (dark)", "com.jtattoo.plaf.noire.NoireLookAndFeel");
        } catch (ClassNotFoundException ex13) {
        }
        try {
            Class.forName("de.javasoft.plaf.synthetica.SyntheticaStandardLookAndFeel", false, ClassLoader.getSystemClassLoader());
            UIManager.installLookAndFeel("Synthetica", "de.javasoft.plaf.synthetica.SyntheticaStandardLookAndFeel");
        } catch (ClassNotFoundException ex14) {
        }
        initCraftingAffixes();
        GDMsgLogger.clear();
        if (logStash.containsMessages()) {
            logStash.addWarning(GDMsgFormatter.getString(GDMsgFormatter.rbMsg, "ERR_STASH_ITEMS_REMOVED"));
            GDMsgLogger.addLog(logStash);
        }

        Lm.verifyLicense("ej-technologies GmbH", "install4j", "cDo6hLbn5vRv8u4gFYLW06CJVkE.x7i1");
    }

    public static boolean isGrimDawnRunning() {
        boolean found = false;
        try {
            final Process p = Runtime.getRuntime().exec(System.getenv("windir") + "\\system32\\tasklist.exe");
            try (final BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
                for (String line = input.readLine(); line != null; line = input.readLine()) {
                    if (line.toUpperCase(GDConstants.LOCALE_US).contains("GRIM DAWN.EXE")) {
                        found = true;
                        break;
                    }
                }
            }
        } catch (IOException ex) {
        }
        return found;
    }

    public TrayIcon trayIcon;

    public GDStashFrame() {
        super("Grim Dawn Stash v1.8.0d - " + System.getProperty("java.vm.name") + " " + System.getProperty("java.version"));
        this.pnlTransfer = new GDTransferPane(GDStashInfoList.defaultStash, this);
        this.pnlCharInventory = new GDCharInventoryPane(this);
        this.pnlCraft = new GDCraftPane(GDStashInfoList.defaultStash, this);
        this.pnlCharEdit = new GDCharEditPane(this);
        this.pnlMasteryInfo = new GDMasteryInfoPane(this);
        this.pnlCollection = new GDCollectionTabbedPane(this);
        this.pnlMassImport = new GDMassImportPane(this);
        this.pnlConfig = new GDConfigPane(this);
        this.pnlTabbed = new GDTabbedPane(this);
        this.setDefaultCloseOperation(0);
        if (SystemTray.isSupported()) {
            this.tray = SystemTray.getSystemTray();
            this.trayMenu = new PopupMenu();
            final MenuItem itemShow = new MenuItem(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "MENU_SHOW"));
            final MenuItem itemExit = new MenuItem(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "MENU_EXIT"));
            this.trayMenu.add(itemShow);
            itemShow.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(final ActionEvent e) {
                    GDStashFrame.this.setVisible(true);
                }
            });
            this.trayMenu.add(itemExit);
            itemExit.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(final ActionEvent e) {
                    final boolean close = GDStashFrame.this.closeFrame();
                    if (close) {
                        System.exit(0);
                    }
                }
            });
            final Image image = Toolkit.getDefaultToolkit().getImage("image" + GDConstants.FILE_SEPARATOR + "GDS_TrayIcon.png");
            this.trayIcon = new TrayIcon(image, "GD Stash", this.trayMenu);
            if (GDStashFrame.iniConfig.sectUI.minimizeToTray) {
                try {
                    this.tray.add(this.trayIcon);
                } catch (Exception ex) {
                    this.tray = null;
                }
            }
        }
        this.addWindowListener(new GDCloseWindowListener());
        this.addWindowStateListener(new GDWindowListener());
        this.addComponentListener(new GDResizeListener());
        if (GDStashFrame.splash != null) {
            GDStashFrame.splash.setVisible(false);
            GDStashFrame.splash.dispose();
            GDStashFrame.splash = null;
        }
        this.setIconImage(GDImagePool.iconLogo64x64.getImage());
        this.add(this.pnlTabbed);
    }

    private static DefaultComboBoxModel<DBAffix> cloneComboBoxModel(final DefaultComboBoxModel<DBAffix> model) {
        final DefaultComboBoxModel<DBAffix> clone = new DefaultComboBoxModel<DBAffix>();
        for (int i = 0; i < model.getSize(); ++i) {
            final DBAffix affix = model.getElementAt(i);
            clone.addElement(affix);
        }
        return clone;
    }

    public static DefaultComboBoxModel<DBAffix> getCompletion() {
        return cloneComboBoxModel(GDStashFrame.dmCompletion);
    }

    public static DefaultComboBoxModel<DBAffix> getModifier() {
        return cloneComboBoxModel(GDStashFrame.dmModifier);
    }

    public static DefaultComboBoxModel<DBAffix> getCelestialModifier() {
        return cloneComboBoxModel(GDStashFrame.dmModifierCelestial);
    }

    public static void setGDLocale(final String language, final GDStashFrame frame) throws IOException {
        GDMsgFormatter.setGDLocale(language);
        adjustUI(frame);
    }

    private static void changeFontRecursive(final Container root, final int fontSize) {
        for (final Component c : root.getComponents()) {
            Font font = c.getFont();
            font = font.deriveFont((float) fontSize);
            c.setFont(font);
            if (c instanceof Container) {
                changeFontRecursive((Container) c, fontSize);
            }
        }
    }

    public static void adjustUI(final GDStashFrame frame) {
        if (frame != null) {
            frame.adjustUI();
        }
    }

    public static void setMnemonic(final AbstractButton ab, final String tag) {
        final String s = GDMsgFormatter.getString(GDMsgFormatter.rbUI, tag);
        if (s == null) {
            return;
        }
        if (s.isEmpty()) {
            return;
        }
        final char c = s.charAt(0);
        switch (c) {
            case 'A': {
                ab.setMnemonic(65);
                break;
            }
            case 'B': {
                ab.setMnemonic(66);
                break;
            }
            case 'C': {
                ab.setMnemonic(67);
                break;
            }
            case 'D': {
                ab.setMnemonic(68);
                break;
            }
            case 'E': {
                ab.setMnemonic(69);
                break;
            }
            case 'F': {
                ab.setMnemonic(70);
                break;
            }
            case 'G': {
                ab.setMnemonic(71);
                break;
            }
            case 'H': {
                ab.setMnemonic(72);
                break;
            }
            case 'I': {
                ab.setMnemonic(73);
                break;
            }
            case 'J': {
                ab.setMnemonic(74);
                break;
            }
            case 'K': {
                ab.setMnemonic(75);
                break;
            }
            case 'L': {
                ab.setMnemonic(76);
                break;
            }
            case 'M': {
                ab.setMnemonic(77);
                break;
            }
            case 'N': {
                ab.setMnemonic(78);
                break;
            }
            case 'O': {
                ab.setMnemonic(79);
                break;
            }
            case 'P': {
                ab.setMnemonic(80);
                break;
            }
            case 'Q': {
                ab.setMnemonic(81);
                break;
            }
            case 'R': {
                ab.setMnemonic(82);
                break;
            }
            case 'S': {
                ab.setMnemonic(83);
                break;
            }
            case 'T': {
                ab.setMnemonic(84);
                break;
            }
            case 'U': {
                ab.setMnemonic(85);
                break;
            }
            case 'V': {
                ab.setMnemonic(86);
                break;
            }
            case 'W': {
                ab.setMnemonic(87);
                break;
            }
            case 'X': {
                ab.setMnemonic(88);
                break;
            }
            case 'Y': {
                ab.setMnemonic(89);
                break;
            }
            case 'Z': {
                ab.setMnemonic(90);
                break;
            }
        }
    }

    public static void messageToList(final String str) {
    }

    public static void listToLog() {
    }

    public static void setApplicationFont(final float size) {
        final Enumeration enumer = UIManager.getDefaults().keys();
        while (enumer.hasMoreElements()) {
            final Object key = enumer.nextElement();
            final Object value = UIManager.get(key);
            if (value instanceof Font) {
                Font font = (Font) value;
                font = font.deriveFont(size);
                UIManager.put(key, font);
            }
        }
    }

    public static void renameCharDir(final File fDirOld, final File fDirNew, final GDStashFrame frame) {
        if (GDCharInfoList.gdCharFileInfos == null) {
            return;
        }
        for (final GDCharInfoList.GDCharFileInfo info : GDCharInfoList.gdCharFileInfos) {
            if (info.charFile != null) {
                final File fDir = info.charFile.getParentFile();
                if (fDir == null) {
                    continue;
                }
                if (!fDir.equals(fDirOld)) {
                    continue;
                }
                try {
                    final String name = info.charFile.getName();
                    final String s = fDirNew.getCanonicalPath() + GDConstants.FILE_SEPARATOR + name;
                    final File f = new File(s);
                    info.charFile = f;
                    if (info.gdChar != null) {
                        info.gdChar.setFileDir(fDirNew);
                    }
                    GDCharInfoList.adjustCharInfo(info);
                } catch (IOException ex) {
                    GDMsgLogger.addError(ex);
                }
            }
        }
    }

    public static void initCraftingAffixes() {
        if (GDStashFrame.iniConfig == null) {
            return;
        }
        if (GDStashFrame.iniConfig.sectHistory == null) {
            return;
        }
        if (GDDBData.doesExist(GDStashFrame.iniConfig.sectHistory.lastMod)) {
            boolean exists = false;
            try {
                if (GDDBUtil.tableExists("GD_AFFIXSET")) {
                    exists = true;
                }
            } catch (SQLException ex) {
                exists = false;
            }
            if (exists) {
                final List<DBAffixSet> craftSets = DBAffixSet.getCraftingAffixes();
                List<DBAffix> craftAffixes = GDItemCraftPane.extractAffixes(null, craftSets, 3);
                if (craftAffixes == null) {
                    craftAffixes = new LinkedList<DBAffix>();
                }
                Collections.<DBAffix>sort(craftAffixes, new DBAffix.AffixComparator());
                final List<DBAffixSet> compSets = DBAffixSet.getCompletionAffixes();
                List<DBAffix> compAffixes = GDItemCraftPane.extractAffixes(null, compSets, 4);
                if (compAffixes == null) {
                    compAffixes = new LinkedList<DBAffix>();
                }
                Collections.<DBAffix>sort(compAffixes, new DBAffix.AffixComparator());
                GDStashFrame.dmCompletion = new DefaultComboBoxModel<DBAffix>();
                GDStashFrame.dmModifier = new DefaultComboBoxModel<DBAffix>();
                GDStashFrame.dmModifierCelestial = new DefaultComboBoxModel<DBAffix>();
                GDStashFrame.dmCompletion.addElement(null);
                GDStashFrame.dmModifier.addElement(null);
                GDStashFrame.dmModifierCelestial.addElement(null);
                for (final DBAffix affix : compAffixes) {
                    if (affix == null) {
                        continue;
                    }
                    if (affix.getAffixType() != 4) {
                        continue;
                    }
                    GDStashFrame.dmCompletion.addElement(affix);
                }
                for (final DBAffix affix : craftAffixes) {
                    if (affix == null) {
                        continue;
                    }
                    if (affix.getAffixType() != 3) {
                        continue;
                    }
                    GDStashFrame.dmModifier.addElement(affix);
                    if (!affix.getAffixID().equals("records/items/lootaffixes/crafting/ac02_healthregen.dbr") && !affix.getAffixID().equals("records/items/lootaffixes/crafting/ad08_da.dbr") && !affix.getAffixID().equals("records/items/lootaffixes/crafting/ao14_oa.dbr")) {
                        continue;
                    }
                    GDStashFrame.dmModifierCelestial.addElement(affix);
                }
            }
        }
    }

    private void adjustUI() {
        if (this.pnlTransfer != null) {
            this.pnlTransfer.adjustUI();
        }
        if (this.pnlCharInventory != null) {
            this.pnlCharInventory.adjustUI();
        }
        if (this.pnlCraft != null) {
            this.pnlCraft.adjustUI();
        }
        if (this.pnlCharEdit != null) {
            this.pnlCharEdit.adjustUI();
        }
        if (this.pnlMasteryInfo != null) {
            this.pnlMasteryInfo.adjustUI();
        }
        if (this.pnlMassImport != null) {
            this.pnlMassImport.adjustUI();
        }
        if (this.pnlCollection != null) {
            this.pnlCollection.adjustUI();
        }
        if (this.pnlConfig != null) {
            this.pnlConfig.adjustUI();
        }
        if (this.pnlTabbed != null) {
            this.pnlTabbed.adjustUI();
        }
    }

    public void checkTabs() {
        if (this.pnlTabbed != null) {
            this.pnlTabbed.checkTabs();
        }
    }

    public void refresh() {
        GDDBData.clearBuffers();
        GDCharInfoList.updateCharSummary();
        if (this.pnlTransfer != null) {
            this.pnlTransfer.refresh();
        }
        if (this.pnlCharInventory != null) {
            this.pnlCharInventory.refresh();
        }
        if (this.pnlCraft != null) {
            this.pnlCraft.refresh();
        }
        if (this.pnlCharEdit != null) {
            this.pnlCharEdit.refresh();
        }
    }

    public boolean closeFrame() {
        boolean stashChanges = false;
        boolean charChanges = false;
        if (GDStashInfoList.gdStashFileInfos != null) {
            for (final GDStashInfoList.GDStashFileInfo info : GDStashInfoList.gdStashFileInfos) {
                if (info.gdStash != null && info.gdStash.hasChanged()) {
                    stashChanges = true;
                    break;
                }
            }
        }
        if (GDCharInfoList.gdCharFileInfos != null) {
            for (final GDCharInfoList.GDCharFileInfo info2 : GDCharInfoList.gdCharFileInfos) {
                if (info2.gdChar != null && info2.gdChar.hasChanged()) {
                    charChanges = true;
                    break;
                }
            }
        }
        if (stashChanges || charChanges) {
            int i = 0;
            final JButton[] buttons = {new JButton(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "BTN_SAVE"), GDImagePool.iconBtnSave24), new JButton(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "BTN_QUIT"), GDImagePool.iconBtnCancel24)};
            String tag = null;
            if (stashChanges && charChanges) {
                tag = "TXT_SAVE_CHANGES_ALL";
            } else if (stashChanges) {
                tag = "TXT_SAVE_CHANGES_STASH";
            } else {
                tag = "TXT_SAVE_CHANGES_CHAR";
            }
            i = GDFlexDialog.showDialog(GDMsgFormatter.getString(GDMsgFormatter.rbUI, tag), buttons, 2, null, true);
            if (i == -1) {
                return false;
            }
            if (i == 0) {
                if (this.isCloudSaveDir() && isGrimDawnRunning()) {
                    GDMsgLogger.addInfo(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "INFO_GD_CLOUD_SAVE"));
                    GDMsgLogger.addInfo(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "INFO_GD_CLOSE"));
                    GDMsgLogger.showLog(this, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "INFO_GD_RUNNING"), GDLog.MessageType.Info, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "INFO_GD_RUNNING"));
                    return false;
                }
                boolean success = true;
                if (stashChanges && GDStashInfoList.gdStashFileInfos != null) {
                    for (final GDStashInfoList.GDStashFileInfo info3 : GDStashInfoList.gdStashFileInfos) {
                        if (info3.gdStash != null && info3.gdStash.hasChanged()) {
                            try {
                                info3.gdStash.write();
                            } catch (Exception ex) {
                                GDMsgLogger.addError(ex);
                                success = false;
                            }
                        }
                    }
                }
                if (charChanges && GDCharInfoList.gdCharFileInfos != null) {
                    for (final GDCharInfoList.GDCharFileInfo info4 : GDCharInfoList.gdCharFileInfos) {
                        if (info4.gdChar != null && info4.gdChar.hasChanged()) {
                            try {
                                info4.gdChar.write();
                            } catch (Exception ex) {
                                GDMsgLogger.addError(ex);
                                success = false;
                            }
                        }
                    }
                }
                if (!success) {
                    GDMsgLogger.showLog(this, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "SUCCESS"), GDLog.MessageType.Error, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "ERROR"));
                    return false;
                }
            }
        }
        if (!(GDStashFrame.iniConfig.sectWindow.maximized = ((this.getExtendedState() & 0x6) == 0x6))) {
            GDStashFrame.iniConfig.sectWindow.x = this.getX();
            GDStashFrame.iniConfig.sectWindow.y = this.getY();
            GDStashFrame.iniConfig.sectWindow.w = this.getWidth();
            GDStashFrame.iniConfig.sectWindow.h = this.getHeight();
        }
        GDStashFrame.iniConfig.writeWindowSection();
        GDDBData.closeConnections();
        return true;
    }

    public String getSaveDir() {
        if (this.pnlConfig == null) {
            return null;
        }
        return this.pnlConfig.getSaveDir();
    }

    public boolean isCloudSaveDir() {
        final String dir = this.getSaveDir();
        return dir != null && dir.contains("219990");
    }

    public String getSelectedMod() {
        if (this.pnlConfig == null) {
            return null;
        }
        return this.pnlConfig.getSelectedMod();
    }

    public static void readDBConfig(final Frame frame) {
        boolean exists = false;
        try {
            exists = GDDBUtil.tableExists("INFO_CONFIG");
        } catch (SQLException ex) {
            exists = false;
            GDMsgLogger.clear();
        }
        if (!exists) {
            try {
                GDDBData.createConfigTables();
            } catch (SQLException ex) {
                GDMsgLogger.addError(ex);
                while (ex.getNextException() != null) {
                    ex = ex.getNextException();
                    GDMsgLogger.addError(ex);
                }
                return;
            }
        }
        DBConfig.reset();
        DBEngineGame.reset();
        DBEnginePlayer.reset();
        DBEngineLevel.reset();
        DBEngineSkillMaster.reset();
        final DBConfig config = DBConfig.get();
        if (config == null) {
            GDStashFrame.dbConfig = new DBConfig();
        } else {
            GDStashFrame.dbConfig = config;
            if (!"1.0.8".equals(config.configVer)) {
                GDStashFrame.dbConfig.configInit = false;
                GDStashFrame.dbConfig.configVer = "1.0.8";
            }
            if (!"1.8.0".equals(config.gddbVer)) {
                GDStashFrame.dbConfig.gddbInit = false;
                GDStashFrame.dbConfig.gddbVer = "1.8.0";
            }
        }
        if (!GDStashFrame.dbConfig.configInit && !GDStashFrame.dbConfig.gddbInit) {
            final GDLogoDialog dialog = new GDLogoDialog(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "TXT_CONFIG_IMPORT"), 2, frame, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "INFORMATION"), true);
            dialog.setVisible(true);
        } else {
            if (!GDStashFrame.dbConfig.configInit) {
                final GDLogoDialog dialog = new GDLogoDialog(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "TXT_CONFIGURE_PROG"), 2, frame, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "INFORMATION"), true);
                dialog.setVisible(true);
            }
            if (!GDStashFrame.dbConfig.gddbInit) {
                final GDLogoDialog dialog = new GDLogoDialog(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "TXT_IMPORT_DB"), 2, frame, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "INFORMATION"), true);
                dialog.setVisible(true);
            }
        }
        if (!GDStashFrame.dbConfig.gddbInit) {
            return;
        }
        final DBEngineGame game = DBEngineGame.get();
        if (game == null) {
            GDStashFrame.engineGame = new DBEngineGame();
        } else {
            GDStashFrame.engineGame = game;
        }
        final DBEnginePlayer player = DBEnginePlayer.get();
        if (player == null) {
            GDStashFrame.enginePlayer = new DBEnginePlayer();
        } else {
            GDStashFrame.enginePlayer = player;
        }
        final DBEngineLevel level = DBEngineLevel.get();
        if (level == null) {
            GDStashFrame.engineLevel = new DBEngineLevel();
        } else {
            GDStashFrame.engineLevel = level;
        }
        GDMasteryInfoPane.initStats();
        GDCharMasteryPane.loadMasteries();
        GDCharMasteryImagePane.initStats();
    }

    private static void test() {
        final Object[] args = {"Test1", 21.3f, 3};
        System.out.println(GDMsgFormatter.format("{2,number,integer}% Chance of {1,number,integer}% {0}", args));
        System.exit(0);
    }

    public static void main(final String[] args) {
        try {
            final UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
            for (int i = 0; i < info.length; ++i) {
                if (info[i].getName().equals(GDStashFrame.iniConfig.sectUI.lookNFeel)) {
                    UIManager.setLookAndFeel(info[i].getClassName());
                    GDColor.setLookAndFeelUI(info[i].getClassName());
                    break;
                }
            }
        } catch (Exception ex) {
        }
        DBAffix.fillBuffer();
        final Starter starter = new Starter();
        SwingUtilities.invokeLater(starter);
    }

    private static class Starter extends Thread {
        @Override
        public void run() {
            GDStashFrame frame = null;
            try {
                frame = new GDStashFrame();
                if (!GDStashFrame.dbConfig.configInit || !GDStashFrame.dbConfig.gddbInit) {
                    GDMsgLogger.clear();
                }
                frame.setLocation(GDStashFrame.iniConfig.sectWindow.x, GDStashFrame.iniConfig.sectWindow.y);
                if (GDStashFrame.iniConfig.sectWindow.maximized) {
                    frame.setExtendedState(frame.getExtendedState() | 0x6);
                } else {
                    frame.setSize(GDStashFrame.iniConfig.sectWindow.w, GDStashFrame.iniConfig.sectWindow.h);
                }
                frame.setVisible(true);
                GDMsgLogger.showLog(frame, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "MESSAGES"), GDLog.MessageType.Info, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "ERRORS"), false, false);
            } catch (Exception ex) {
                if (frame == null) {
                    String s = null;
                    if (ex.getMessage() == null || ex.getMessage().isEmpty()) {
                        s = ex.toString();
                    } else {
                        s = ex.getMessage();
                    }
                    if (s == null) {
                        s = GDMsgFormatter.getString(GDMsgFormatter.rbUI, "ERR_UNEXPECTED");
                    }
                    s = s + GDConstants.LINE_SEPARATOR + GDLog.getStackTrace(ex);
                    JOptionPane.showMessageDialog(null, s, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "ERROR"), 0);
                    System.exit(1);
                } else {
                    GDMsgLogger.addError(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "ERR_EXCEPTION"));
                    GDMsgLogger.addError(ex);
                    final String s = GDLog.getStackTrace(ex);
                    GDMsgLogger.addError(s);
                    GDMsgLogger.showLog(frame, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "SUCCESS"), GDLog.MessageType.Error, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "ERROR"));
                    System.exit(1);
                }
            }
        }
    }

    private class GDCloseWindowListener extends WindowAdapter {
        @Override
        public void windowClosing(final WindowEvent e) {
            if (GDStashFrame.iniConfig.sectUI.minimizeToTray && GDStashFrame.this.tray != null) {
                GDStashFrame.this.setDefaultCloseOperation(1);
                return;
            }
            final boolean close = GDStashFrame.this.closeFrame();
            if (close) {
                final GDStashFrame frame = (GDStashFrame) e.getSource();
                frame.setDefaultCloseOperation(3);
            }
        }
    }

    private class GDWindowListener implements WindowStateListener {
        @Override
        public void windowStateChanged(final WindowEvent e) {
            if (e.getNewState() == 0) {
                final Window w = e.getWindow();
                w.setLocation(GDStashFrame.iniConfig.sectWindow.x, GDStashFrame.iniConfig.sectWindow.y);
                w.setSize(GDStashFrame.iniConfig.sectWindow.w, GDStashFrame.iniConfig.sectWindow.h);
            }
        }
    }

    private class GDResizeListener extends ComponentAdapter {
        @Override
        public void componentResized(final ComponentEvent e) {
            final JFrame frame = (JFrame) e.getComponent();
            final boolean maximized = (frame.getExtendedState() & 0x6) == 0x6;
            if (!maximized) {
                GDStashFrame.iniConfig.sectWindow.x = frame.getX();
                GDStashFrame.iniConfig.sectWindow.y = frame.getY();
                GDStashFrame.iniConfig.sectWindow.w = frame.getWidth();
                GDStashFrame.iniConfig.sectWindow.h = frame.getHeight();
            }
        }
    }
}
